package com.report.wx.mp;


import com.binarywang.spring.starter.wxjava.mp.properties.WxMpProperties;
import com.report.wx.mp.handler.ScanHandler;
import com.report.wx.mp.handler.SubscribeHandler;
import com.report.wx.mp.handler.UnSubscribeHandler;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author summer
 * @date 2023-09-06 15:17
 */
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
@ConditionalOnClass({WxMpProperties.class})
@AllArgsConstructor
public class WxMpConfiguration {

    private  final   WxMpProperties wxMpProperties;

    private final SubscribeHandler subscribeHandler;

    private final UnSubscribeHandler unSubscribeHandler;
    /**
     * 微信客户端配置存储
     */
    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        // 设置微信公众号appId
        configStorage.setAppId(wxMpProperties.getAppId());
        // 设置微信公众号appSecret
        configStorage.setSecret(wxMpProperties.getSecret());
        // 设置微信公众号的token
        configStorage.setToken(wxMpProperties.getToken());
        // 设置微信公众号的EncodingAESKey
        configStorage.setAesKey(wxMpProperties.getAesKey());
        return configStorage;
    }


    /**
     * WxMpService多个实现类 声明一个实例
     */
    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    private  final ScanHandler scanHandler;

    @Bean
    public WxMpMessageRouter wxMessageRouter() {
        WxMpMessageRouter router = new WxMpMessageRouter(wxMpService());
        //增加关注
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SUBSCRIBE).handler(subscribeHandler).end();
        //取消关注
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.UNSUBSCRIBE).handler(unSubscribeHandler).end();

        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SCAN).handler(scanHandler).end();


        return router;
    }

}
